package com.ehotting.mqbd.core.manager;

import com.ehotting.eaf.core.StringHelper;
import com.ehotting.mqbd.api.bean.MQDataAble;
import com.ehotting.mqbd.api.bean.MsgStateBean;
import com.ehotting.mqbd.api.bean.solver.SolverStateBean;
import com.ehotting.mqbd.api.enums.DirectionEnum;
import com.ehotting.mqbd.core.service.MQService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public abstract class QueueNotifyAgentAble {

    private  final Logger logger = LoggerFactory.getLogger(QueueNotifyAgentAble.class);

    private MsgStateManager msgStateManager;
    private MqQueueManager mqQueueManager;
    private AgentLinkManager agentLinkManager;

    private MQService mqService;

    public QueueNotifyAgentAble(MqQueueManager mqQueueManager,
                                MsgStateManager msgStateManager,
                                AgentLinkManager agentLinkManager,
                                MQService mqService){
        this.mqQueueManager = mqQueueManager;
        this.msgStateManager = msgStateManager;
        this.agentLinkManager = agentLinkManager;
        this.mqService = mqService;
    }

    public void invoke(MQDataAble mqData,List<MsgStateBean> msgStateList, SolverStateBean solverState){
        logger.info("Start invoke.");

        for(int index=0 ; index<msgStateList.size() ; index++){
            MsgStateBean msgState = msgStateList.get(index);
            logger.info("Module[agentId:{}] get index:{}.",msgState.getAgentId(),index);
            MQDataAble data = genQueueMsg(index,msgState,solverState);
            sendToClient(data,msgState,index);
        }
        logger.info("Finish invoke.");
    }

    private void sendToClient(MQDataAble mqData,MsgStateBean msgState,int redisQueueIndex){

        String clientIp = agentLinkManager.getClientIpByAgentId(msgState.getAgentId());
        logger.info("clientIp:{}.",clientIp);
        if(StringHelper.isBlank(clientIp)){
            logger.info("clientIp is null,getByMsgId by agentId[{}],return.",msgState.getAgentId());
            return;
        }

        if(mqData==null){
            logger.error("mqData is null,redisQueueIndex:{},agentId:{},return.",redisQueueIndex,msgState.getAgentId());
            return;
        }

        mqData.setConsumerHost(clientIp);
        mqData.setAgentId(msgState.getAgentId());
        mqData.setDirection(DirectionEnum.RESPONSE.getCode());
        mqService.request(mqData);
    }


    public abstract MQDataAble genQueueMsg(long index, MsgStateBean msgState, SolverStateBean solverState);

}
